import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { SystemDeptDataItemType, SystemDeptStateType } from './typings'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElButton,
  ElLink,
  ElIcon,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { View, EditPen, Delete, Plus, CirclePlus } from '@element-plus/icons-vue'
import { handleTrim } from '~/utils/util'
import type { tenantSelectEnum } from '~/store/system/typings'
import { cloneDeep } from 'lodash'
import ProSaasTable from '~/components/ProSaasTable'
import SearchForm from '~/components/ProForm/SearchForm'
import useVuexGetters from '~/hooks/useVuexGetters'
import SystemDeptOptionsModal from './options'
import SystemDeptPost from './deptPost'

export default defineComponent(function systemDept() {
  const store = useStore()
  // 初始值
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<SystemDeptDataItemType>({})
  const state = reactive<SystemDeptStateType>({
    modalVisible: false,
    deptPostVisible: false,
    type: 'read',
    record: {},
    rowId: '',
    treeWordsListVlaue: []
  })

  const systemPostState = useVuexGetters('systemPost', ['tenantSelectList', 'tenantSelectEnum'])
  const getCurrentTenant = useVuexGetters('user', ['userAddressInfo'])
  const userState = useVuexGetters('user', ['permission'])

  onMounted(async () => {
    store.dispatch('systemPost/GetTenantSelect') // 所属租户
  })

  // methods
  // 上级部门 传租户id
  const getSystemDeptTreeAjax = async (value: string) => {
    const res = await store.dispatch('systemDept/GetSystemDeptTree', { tenantId: value })
    state.treeWordsListVlaue = res.data
  }

  // 增改查
  const handleChangeOptionsModal = (
    type: SystemDeptStateType['type'],
    record?: SystemDeptDataItemType
  ) => {
    state.record = record || {}
    state.type = type
    if (!state.modalVisible && type === 'add') {
      // '新增' 时 无行数据传来 故取当前登录的租户id
      getSystemDeptTreeAjax(getCurrentTenant.userAddressInfo.value.tenantId) // 更新上级部门
    }
    if (!state.modalVisible && record) {
      // 有行数据传来时 弹窗显示时才调 '上级部门' 接口
      getSystemDeptTreeAjax(record.tenantId!) // 更新上级部门
    }
    state.modalVisible = !state.modalVisible
    if (!state.modalVisible) {
      proSaasTableRef.value!?.toSearch() // 更新主列表
    }
  }

  // 删除
  const handleOpenDeleteConfirm = (record?: SystemDeptDataItemType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择至少一条数据' })
      return
    }
    let params = ''
    if (record?.id) {
      params = record?.id
    } else {
      const element = cloneDeep(proSaasTableRef.value?.selecteds)
      const idsArr = element.map((item: { id: string }) => item.id) // 存待删的id们
      params = idsArr.join(',')
    }
    ElMessageBox.confirm('确定将选择数据删除?', {
      buttonSize: 'small',
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('systemDept/PostSystemDeptRemove', params).then((res) => {
          if (res?.code === 200) {
            proSaasTableRef.value!?.toSearch()
            getSystemDeptTreeAjax(record?.tenantId!) // 更新上级部门
            ElMessage({ type: 'success', message: '操作成功' })
          } else {
            ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
          }
        })
      })
      .catch(() => {})
  }

  // 部门岗位
  const deptPost = (record?: SystemDeptDataItemType) => {
    state.deptPostVisible = !state.deptPostVisible
    state.record = record || {}
    state.rowId = record?.id || ''
    if (!state.modalVisible) {
      proSaasTableRef.value!?.toSearch() // 更新主列表
    }
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }

  // 清空/下拉框值变 搜索
  const searchTable = () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  const columns: TableColumnProps<SystemDeptDataItemType>[] = [
    {
      label: '部门名称',
      prop: 'deptName',
      minWidth: 180,
      showOverflowTooltip: true
    },
    {
      label: '所属租户',
      prop: 'tenantId',
      minWidth: 180,
      enumValues: systemPostState.tenantSelectEnum,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '部门全称',
      prop: 'fullName',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '上级部门',
      prop: 'parentName',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '排序',
      prop: 'sort',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '备注',
      prop: 'remark',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '操作',
      prop: 'options',
      fixed: 'right',
      unFixed: true,
      minWidth: 180,
      width: 460,
      align: 'center',
      render: ({ row }) => {
        return (
          <>
            {userState.permission.value.has('system_dept_view') && (
              <ElLink type="primary" onClick={() => handleChangeOptionsModal('read', row)}>
                <ElIcon>
                  <View />
                </ElIcon>
                &nbsp;查看
              </ElLink>
            )}
            &nbsp;&nbsp;&nbsp;
            {userState.permission.value.has('system_dept_update') && (
              <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
                <ElIcon>
                  <EditPen />
                </ElIcon>
                &nbsp;编辑
              </ElLink>
            )}
            &nbsp;&nbsp;&nbsp;
            {userState.permission.value.has('system_dept_remove') && (
              <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
                <ElIcon>
                  <Delete />
                </ElIcon>
                &nbsp;删除
              </ElLink>
            )}
            &nbsp;&nbsp;&nbsp;
            {userState.permission.value.has('system_dept_addSon') && (
              <ElLink type="primary" onClick={() => handleChangeOptionsModal('addSon', row)}>
                <ElIcon>
                  <CirclePlus />
                </ElIcon>
                &nbsp;新增子项
              </ElLink>
            )}
            &nbsp;&nbsp;&nbsp;
            {userState.permission.value.has('system_dept_post') && (
              <ElLink type="primary" onClick={() => deptPost(row)}>
                <ElIcon>
                  <CirclePlus />
                </ElIcon>
                &nbsp;部门岗位
              </ElLink>
            )}
          </>
        )
      }
    }
  ]

  return () => {
    return (
      <ElCard>
        <SearchForm
          searchFormProps={{
            model: formValues
          }}
          searchformResponsiveCol={[
            <ElFormItem key="deptName" prop="deptName" label="部门名称：">
              <ElInput
                v-model={formValues.deptName}
                placeholder="请输入 部门名称"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={searchTable}
              />
            </ElFormItem>,
            <ElFormItem key="tenantId" prop="tenantId" label="所属租户：">
              <ElSelect
                v-model={formValues.tenantId}
                placeholder="请选择 或输入关键字"
                filterable
                clearable
                onChange={searchTable}
              >
                {systemPostState.tenantSelectList?.value?.map((item: tenantSelectEnum) => (
                  <ElOption key={item?.tenantId} label={item?.tenantName} value={item?.tenantId} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="fullName" prop="fullName" label="部门全称：">
              <ElInput
                v-model={formValues.fullName}
                placeholder="请输入 部门全称"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={searchTable}
              />
            </ElFormItem>
          ]}
          handleSearchList={proSaasTableRef.value?.toSearch}
        />
        <ProSaasTable<SystemDeptDataItemType>
          ref={proSaasTableRef}
          columns={columns}
          rowKey="id"
          lazy
          treeProps={{ children: 'children', hasChildren: 'hasChildren' }}
          hasIndex
          hasSelection
          searchParams={{
            deptName: formValues.deptName && handleTrim(formValues.deptName),
            fullName: formValues.fullName && handleTrim(formValues.fullName)
          }}
          searchFormProps={{
            model: formValues
          }}
          dispatchType="systemDept/GetSystemDeptList"
          dispatchTypeGetListKeys="data"
          headerTitle={
            <>
              {userState.permission.value.has('system_dept_add') && (
                <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  &nbsp; 新增
                </ElButton>
              )}
              {/* // 批量删除 暂隐藏 */}
              {/* <ElButton type="danger" plain onClick={() => handleOpenDeleteConfirm()}>
                <ElIcon>
                  <Delete />
                </ElIcon>
                &nbsp; 删除
              </ElButton> */}
            </>
          }
        />
        {state.modalVisible && ( // 操作列 弹窗
          <SystemDeptOptionsModal
            visible={state.modalVisible}
            type={state.type}
            record={state.record}
            treeWordsListVlaue={state.treeWordsListVlaue}
            onCancel={() => handleChangeOptionsModal('read')}
          />
        )}
        {state.deptPostVisible && ( // 部门岗位 弹窗
          <SystemDeptPost
            visible={state.deptPostVisible}
            rowId={state.rowId}
            onCancel={() => deptPost()}
          />
        )}
      </ElCard>
    )
  }
})
